<template>
  <!--  <div>-->
  <!--    <el-card shadow="never">-->
  <!--      <el-skeleton :loading="loading" animated>-->
  <!--        <el-row :gutter="16" justify="space-between">-->
  <!--          <el-col :xl="18" :lg="18" :md="18" :sm="24" :xs="24">-->
  <!--            <div class="flex items-center">-->

  <!--            </div>-->
  <!--          </el-col>-->
  <!--        </el-row>-->
  <!--      </el-skeleton>-->
  <!--    </el-card>-->
  <!--  </div>-->

  <el-row class="mt-8px" :gutter="8" justify="space-between">
    <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-8px">
      <!-- 涉及人员卡片区域 - 优化局部刷新 -->
      <el-card shadow="never" class="mt-8px">
        <template #header>
          <div class="h-3 flex justify-between items-center">
            <div class="header-title">
              <span>我关注的人员</span>
            </div>
            <el-pagination
              small
              layout="prev, pager, next"
              :total="total"
              :page-size="queryParams.pageSize"
              :current-page="queryParams.pageNo"
              @current-change="handlePersonPageChange"
              :pager-count="5"
              class="person-pagination"
            />
          </div>
        </template>
        <!-- 添加key实现分页变化时只更新该区域 -->
        <div :key="`person-list-${queryParams.pageNo}`">
          <el-skeleton :loading="loading" animated>
            <el-row>
              <el-col
                v-for="(item, index) in list"
                :key="`card-${item.id || index}`"
                :xl="8"
                :lg="8"
                :md="8"
                :sm="24"
                :xs="24"
              >
                <el-card shadow="hover" class="mr-5px mt-5px relative">
                  <!-- 右上角徽标 -->
                  <div class="absolute right-10px top-10px bottom-5px flex space-x-2">
                    <el-badge :value="item.unreadTotal" title="未读预警数量" type="danger"
                              class="custom-badge"/>
                    <el-badge :value="item.warnCount" title="总预警数量" type="info"
                              class="custom-badge"/>
                  </div>
                  <div class="flex items-start"> <!-- 使用items-start确保顶部对齐 -->
                    <!-- 头像区域 -->
                    <div @click="openMemberDetail(item.id)" class="cursor-pointer mr-4">
                      <img :src="item.avatar" style="width: 50px; height: 50px;" alt="用户头像"/>
                    </div>

                    <!-- 右侧文本区域 -->
                    <div class="flex-1 min-w-0">
                      <!-- 第一行：姓名和群组标签 -->
                      <div class="flex items-center flex-wrap gap-2 mb-1">
                        <span class="text-16px font-medium truncate">{{ item.name }}</span>
                        <div v-if="item.groupName"
                             class="text-13px bg-blue-50 text-blue-600 px-3 py-1 rounded-full shadow-sm border border-blue-100">
                          {{ item.groupName }}
                        </div>
                      </div>

                      <!-- 第二行：证件号码 -->
                      <div v-if="item.paperNumber" class="text-12px text-gray-500">
                        {{ item.paperNumber }}
                      </div>
                    </div>
                  </div>

                  <div class="mt-12px flex justify-between text-12px text-gray-400">
                    <span>{{ item.lastLocation }}</span>
                    <span>{{ item.lastLocationTime }}</span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-skeleton>
        </div>
      </el-card>
      <el-card shadow="never" class="mt-8px">
        <el-skeleton :loading="loading" animated>
          <el-row :gutter="20" justify="space-between">
            <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <el-skeleton :loading="loading" animated>
                  <Echart :options="pieOptionsData" :height="280"/>
                </el-skeleton>
              </el-card>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never" class="mt-8px">
        <template #header>
          <div class="h-3 flex justify-between items-center flex-wrap gap-4">
            <div class="header-title">
              <span>最新预警</span>
            </div>
            <el-pagination
              small
              layout="prev, pager, next"
              :total="warnTotal"
              :current-page="queryWarnParams.pageNo"
              @current-change="handleWarnPageSizeChange"
              class="person-pagination"
              :pager-count="3"
            />
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <!-- 通知列表部分保持不变 -->
          <div v-for="(item, index) in warnList" :key="`dynamics-${index}`">
            <div class="flex items-start cursor-pointer">
              <!-- 头像区域 -->
              <el-avatar :size="35" class="mr-16px mt-2" @click="openMemberDetail(item.personId)">
                <img
                  :src="item.avatar || require('../../../../assets/imgs/avatar.gif')"
                  alt="用户头像"
                  @error="item.avatar = require('../../../../assets/imgs/avatar.gif')"
                />
              </el-avatar>

              <!-- 右侧文本区域 -->
              <div class="flex-1">
                <!-- 人员姓名 -->
                <div class="text-14px font-medium text-gray-800 mb-1 flex items-center">
                  <span>{{ item.personName || '未知人员' }}</span>
                  <span class="text-12px text-gray-400 ml-3 truncate">{{
                      item.idNumber || '未填写'
                    }}</span>
                </div>
                <!-- 预警类型和内容 -->
                <div class="text-14px mb-1">
<!--                  <Highlight :keys="item.keys" @click="handleDetailClick(item)">-->
<!--                    【{{ item.type }}】 {{ item.title }} {{ item.warnPersonCountText }}-->
<!--                  </Highlight>-->
                  <Highlight :keys="item.keys">
                    【{{ item.type }}】 {{ item.title }} {{ item.warnPersonCountText }}
                  </Highlight>
                </div>

                <!-- 时间信息 -->
                <div class="text-12px text-gray-400">
                  {{ formatTime(item.date, 'yyyy-MM-dd HH:mm:ss') }}
                </div>
              </div>
            </div>
            <el-divider v-if="index !== warnList.length - 1"/>
          </div>

          <!-- 空状态处理 -->
          <div v-if="!loading && warnList.length === 0" class="text-center py-10">
            <div class="text-gray-400">暂无预警记录</div>
          </div>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
  <el-dialog
    v-model="showMapDialog"
    title="预警点地图详情"
    :width="'70%'"
    :max-height="'90vh'"
    :fullscreen="false"
    :close-on-click-modal="false"
    ref="mapDialogRef"
    class="draggable-dialog fixed-size-dialog"
  >
    <div class="map-dialog-container">
      <div id="map" ref="mapRef" class="map"></div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import {nextTick, onMounted, reactive, ref} from 'vue'
import {useI18n} from 'vue-i18n'
import {set} from 'lodash-es'
import {EChartsOption} from 'echarts'
// 确保已安装此依赖
import {CasesApi, UnifiedWarningDTO, WarningTypeCountDTO} from '@/api/member/cases'
import {formatTime} from '@/utils'
import {PersonCaseInfo, WarnCommon} from './types'
import {pieOptions} from './echarts-data'
import Echart from "@/components/Echart/src/Echart.vue";
import Highlight from '@/components/Highlight/src/Highlight.vue' // 假设你有这个高亮组件
import * as UserApi from '@/api/member/user'
import {useMessage} from "@/hooks/web/useMessage";
import {ElMessage} from "element-plus";
import L from "leaflet";
import {formatToDateTime} from "@/utils/dateUtil";
import {MapPolygonApi} from '@/api/member/map/mapConfigApi'

defineOptions({name: 'Home'})

const {t} = useI18n()
const router = useRouter()

// ======================== 地图相关状态 ========================
const mapRef = ref<HTMLDivElement | null>(null)
// const mapDialogRef = ref<InstanceType<any> | null>(null)
let mapInstance: L.Map | null = null
let polygonLayer: L.FeatureGroup<L.Polygon> | null = null
let warningMarker: L.Marker | null = null
const isLoadingPolygons = ref(false)
// 多边形相关状态
const polygons = ref<MapPolygon[]>([])
const areaUnit = ref<'sqm' | 'sqkm' | 'sqmi'>('sqm')

const showMapDialog = ref(false)
const currentWarning = ref<WarnCommon | null>(null)
const selectedConfigId = ref()

// 分页数据 - 统一使用queryParams管理
const loading = ref(true)
const listLoading = ref(true)
const total = ref(0)
const warnTotal = ref(0)
const list = ref<PersonCaseInfo[]>([])
const message = useMessage()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 12,
})

// ======================== 类型定义 ========================
interface MapPolygon {
  id?: string
  configId: string
  name: string
  strokeColor: string
  strokeWeight: number
  fillColor: string
  fillOpacity: number
  roomLevel: 13
  sortOrder: number
  points: Array<{ ringIndex: number; lng: number; lat: number; pointIndex: number }>
  coordinates: number[][][]
  area?: number
  pointCount?: number
}

// 图表数据
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption

// 最新预警
const warnList = reactive<WarnCommon[]>([])

/** 查询列表 - 只更新人员列表数据 */
const getList = async () => {
  listLoading.value = true
  try {
    const data = await UserApi.getCaseUserPage(queryParams)
    list.value = data.list // 仅更新列表数据
    total.value = data.total
  } finally {
    listLoading.value = false
  }
}

// 分页变化处理 - 仅更新分页参数并刷新列表
const handlePersonPageChange = (page: number) => {
  queryParams.pageNo = page
  getList() // 只重新获取人员列表，不影响其他组件
}

const handleWarnPageSizeChange = (page: number) => {
  queryWarnParams.pageNo = page
  getWarnPage()
}

const openMemberDetail = (id: number) => {
  router.push({name: 'MemberUserDetail', params: {id}})
}

const queryWarnParams = reactive({
  pageNo: 1,
  pageSize: 8,
})

// 获取通知公告 - 修改为调用真实API
const getWarnPage = async () => {
  warnList.length = 0
  try {
    // 调用API获取最新预警数据
    const response = await CasesApi.getCaseHomeLatestWarnPage(queryWarnParams)
    const warnings: UnifiedWarningDTO[] = response.list;
    warnTotal.value = response.total;

    // 转换为页面所需的格式
    warnings.forEach(warn => {
      // 确定预警类型文本
      let warnTypeText: string
      let gatherPersonCountText = ''
      let content = '';
      switch (warn.warnType) {
        case 1:
          warnTypeText = '围栏预警'
          content = warn.warningContent || `定位地址: ${warn.address || '未知'}`
          break
        case 2:
          warnTypeText = '聚集预警-' + warn.gatherName
          gatherPersonCountText = '聚集人数：' + warn.warnPersonCount
          content = warn.warningContent || `定位地址: ${warn.address || '未知'}`
          break
        case 3:
          warnTypeText = '出入杭预警'
          content = warn.warningContent
          break
        case 4:
          warnTypeText = '接入预警'
          break
        default:
          warnTypeText = '未知预警'
      }

      // 确定时间字段（优先使用预警时间，没有则使用定位时间）
      const time = warn.warningTime || warn.locationTime
      warnList.push({
        title: content,
        type: warnTypeText,
        warnType: warn.warnType,
        warningContent: warn.warningContent,
        keys: [warnTypeText, ...content.split(/\s+/), gatherPersonCountText],
        date: time ? new Date(time) : new Date(),
        idNumber: warn.idNumber,
        personName: warn.personName,
        avatar: warn.avatar,

        personId: warn.personId,
        gatherId: warn.gatherId,
        configId: warn.warningConditionId,
        address: warn.address,
        warnPersonCountText: gatherPersonCountText,
        warnPersonCount: warn.warnPersonCount,
        gatherName: warn.gatherName, // 聚集条件名称
        startTime: warn.startTime, // 聚集开始时间
        endTime: warn.endTime, // 聚集结束时间
        gatherAddress: warn.gatherAddress, // 聚集地址
        createTime: warn.createTime,

        fenceType: warn.fenceType,
        lng: warn.lng,
        lat: warn.lat
      })
    })
  } catch (error) {
    console.error('获取最新预警失败:', error)
  }
}

// 用户来源图表
const getWarnTypePie = async () => {
  try {
    // 调用后端API获取真实数据
    const response = await CasesApi.countHomeTodayWarningsByType();

    if (response) {
      // 格式化数据用于饼图
      const pieList: WarningTypeCountDTO[] = response;
      const data = pieList.map(item => ({
        value: item.count,
        name: item.warnTypeName,
        warnType: item.warnType
      }));

      // 更新图表数据
      set(pieOptionsData, 'legend.data', data.map(v => t(v.name)));
      pieOptionsData.series![0].data = data.map(v => ({
        name: t(v.name),
        value: v.value
      }));
    } else {
      console.error('获取预警类型统计失败', response);
      // 显示默认数据
      const defaultData = [
        {value: 335, name: '围栏预警', warnType: 1},
        {value: 310, name: '聚集预警', warnType: 2},
        {value: 234, name: '出入杭预警', warnType: 3},
        {value: 24, name: '接入预警', warnType: 4},
      ];
      set(pieOptionsData, 'legend.data', defaultData.map(v => t(v.name)));
      pieOptionsData.series![0].data = defaultData.map(v => ({
        name: t(v.name),
        value: v.value
      }));
    }
  } catch (error) {
    console.error('获取预警类型统计异常', error);
    // 显示默认数据
    const defaultData = [
      {value: 335, name: '围栏预警', warnType: 1},
      {value: 310, name: '聚集预警', warnType: 2},
      {value: 234, name: '出入杭预警', warnType: 3},
      {value: 24, name: '接入预警', warnType: 4},
    ];
    set(pieOptionsData, 'legend.data', defaultData.map(v => t(v.name)));
    pieOptionsData.series![0].data = defaultData.map(v => ({
      name: t(v.name),
      value: v.value
    }));
  }
}

// 处理详情点击事件
const handleDetailClick = (row: WarnCommon) => {
  if (row.warnType === 1) {
    handleViewMap(row); // 类型1调用地图查看
  } else if (row.warnType === 2) {
    openGatherDetail(row); // 类型2调用聚集详情
  }
  // 其他类型不执行任何操作
};

const handleViewMap = (row: WarnCommon) => {
  if (!row.lng || !row.lat) {
    ElMessage.warning('当前预警点坐标缺失，无法显示地图')
    return
  }

  // 赋值当前预警数据
  currentWarning.value = row
  selectedConfigId.value = row.configId
  showMapDialog.value = true

  // 弹窗渲染完成后初始化地图
  nextTick(() => {
    if (row.warnType === 1) {
      // 围栏地图
      initMap(row.lng, row.lat)
      // 加载对应预警条件的围栏
      loadPolygonsByConfigId(selectedConfigId.value)
    } else {

    }

  })
}

// ======================== 工具方法 ========================
/** 显示状态消息 */
const setMessage = (text: string, duration = 3000) => {
  ElMessage({
    message: text,
    type: 'info',
    duration
  })
}

// ======================== 地图操作方法 ========================
/** 初始化地图 */
const initMap = (centerLng: number, centerLat: number, zoom = 15) => {
  if (!mapRef.value) {
    setMessage('地图容器未找到', 3000)
    return
  }

  // 清除现有地图实例
  if (mapInstance) {
    mapInstance.remove()
  }

  // 创建新地图实例（定位到预警点）
  mapInstance = L.map(mapRef.value, {
    minZoom: 10,
    maxZoom: 18,
    crs: L.CRS.EPSG3857,
    attributionControl: true
  }).setView([centerLat, centerLng], zoom)

  // 加载离线地图瓦片
  L.tileLayer(import.meta.env.VITE_MAP_TILE_URL, {
    errorTileUrl: '',
    attribution: '地图数据 © 高德地图',
    tileSize: 256,
    zoomOffset: 0
  }).addTo(mapInstance);
  // L.tileLayer('http://localhost:8000/map/{z}/{x}/{y}/tile.png', {
  //   errorTileUrl: '',
  //   attribution: '地图数据 © 高德地图',
  //   tileSize: 256,
  //   zoomOffset: 0
  // }).addTo(mapInstance)

  // 初始化多边形图层
  polygonLayer = L.featureGroup<L.Polygon>().addTo(mapInstance)
  // initDrawControl()

  // 添加预警点标记
  addWarningMarker()
}

/** 添加预警点标记 */
const addWarningMarker = () => {
  if (!mapInstance || !currentWarning.value) return

  const {lng, lat, personName, date, warningContent, fenceType} = currentWarning.value
  // 清除现有预警点标记
  if (warningMarker) {
    mapInstance.removeLayer(warningMarker)
  }

  // 转换fenceType为文字描述
  const fenceTypeText = fenceType === 1 ? '禁入围栏' :
    fenceType === 2 ? '禁出围栏' :
      `未知类型(${fenceType})`

  const warnTimeText = formatToDateTime(date)

  // 自定义预警点图标
  const warningIcon = L.divIcon({
    className: 'warning-point-marker',
    html: `
      <div style="
        width: 40px;
        height: 40px;
        background-color: #ff4d4f;
        border: 2px solid white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        box-shadow: 0 2px 10px rgba(255, 77, 79, 0.6);
      ">
        <i class="el-icon-user" style="font-size: 20px;"></i>
      </div>
      <div style="
        position: absolute;
        bottom: -90px;
        left: 50%;
        transform: translateX(-50%);
        background-color: white;
        padding: 2px 6px;
        border-radius: 4px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        white-space: nowrap;
        font-size: 12px;
        color: #333;
      ">
        ${personName}
      </div>
    `,
    iconSize: [40, 120], // 增加图标高度以适应更长的标签
    iconAnchor: [20, 40]
  })

  // 创建标记并添加到地图
  warningMarker = L.marker([lat, lng], {icon: warningIcon, zIndexOffset: 3000}).addTo(mapInstance)
  // 绑定弹窗，包含新增的三个内容
  warningMarker.bindPopup(`
    <div style="width: 280px; padding: 5px 0;">
      <p><strong>人员姓名：</strong>${personName}</p>
      <p><strong>预警时间：</strong>${warnTimeText || '无数据'}</p>
      <p><strong>预警内容：</strong>${warningContent || '无数据'}</p>
      <p><strong>预警类型：</strong>${fenceTypeText}</p>
    </div>
  `).openPopup()
}

/** 加载围栏多边形 */
const loadPolygonsByConfigId = async (configId: string) => {
  if (!configId) {
    setMessage('预警条件ID为空，无法加载围栏', 3000)
    return Promise.reject(new Error('configId is empty'))
  }

  if (isLoadingPolygons.value) return Promise.resolve()
  isLoadingPolygons.value = true

  try {
    console.log('正在加载围栏数据...')
    const res = await MapPolygonApi.getPolygonsByConfigId(configId)

    if (res?.length) {
      polygons.value = res.map((poly: any) => ({
        ...poly,
        pointCount: poly.points?.length || 0,
        area: poly.area || calculatePolygonArea(
          poly.points
            ?.filter((p: any) => p.ringIndex === 0)
            .sort((a: any, b: any) => a.pointIndex - b.pointIndex)
            .map((p: any) => [p.lng, p.lat] as [number, number]) || []
        )
      }))

      renderPolygons()
      // setMessage(`已加载${res.length}个围栏`, 3000)
    } else {
      polygons.value = []
      polygonLayer?.clearLayers()
      setMessage('当前预警条件下无围栏数据', 3000)
    }

    return Promise.resolve()
  } catch (error) {
    setMessage('加载围栏失败', 3000)
    console.error('加载多边形错误:', error)
    return Promise.reject(error)
  } finally {
    isLoadingPolygons.value = false
  }
}

/** 计算多边形面积（球面积分算法） */
const calculatePolygonArea = (points: [number, number][]): number => {
  if (points.length < 3) return 0

  const R = 6378137 // 地球半径（米）
  let area = 0
  const radPoints = points.map(([lng, lat]) => [lng * Math.PI / 180, lat * Math.PI / 180])
  const n = radPoints.length

  for (let i = 0; i < n; i++) {
    const j = (i + 1) % n
    const [lng1, lat1] = radPoints[i]
    const [lng2, lat2] = radPoints[j]
    const dLng = lng2 - lng1
    area += dLng * (2 + Math.sin(lat1) + Math.sin(lat2))
  }

  return Math.abs(area * R * R / 2)
}

/** 格式化面积显示 */
const formatArea = (area: number): string => {
  switch (areaUnit.value) {
    case 'sqkm':
      return (area / 1000000).toFixed(6)
    case 'sqmi':
      return (area / 2589988.11).toFixed(6)
    default:
      return area.toFixed(2)
  }
}

/** 获取面积单位标签 */
const getAreaUnitLabel = (): string => {
  switch (areaUnit.value) {
    case 'sqkm':
      return '平方公里'
    case 'sqmi':
      return '平方英里'
    default:
      return '平方米'
  }
}

/** 渲染多边形到地图 */
const renderPolygons = () => {
  if (!mapInstance || !polygonLayer) return

  // 清空并重新渲染多边形图层
  polygonLayer.clearLayers()

  polygons.value.forEach(poly => {
    const ringMap: Record<number, L.LatLng[]> = {}
    poly.points.forEach((p: any) => {
      const ringIndex = p.ringIndex || 0
      if (!ringMap[ringIndex]) ringMap[ringIndex] = []
      ringMap[ringIndex].push(L.latLng(p.lat, p.lng))
    })

    const latLngs = Object.keys(ringMap)
      .sort((a, b) => Number(a) - Number(b))
      .map(key => ringMap[Number(key)])

    // 错误1修复：使用非空断言操作符!，因为已在函数开头检查过polygonLayer不为null
    const layer = L.polygon(latLngs, {
      color: poly.strokeColor,
      weight: poly.strokeWeight,
      fillColor: poly.fillColor,
      fillOpacity: poly.fillOpacity,
      zIndexOffset: poly.roomLevel || 0
    }).addTo(polygonLayer!)

    layer.bindPopup(`<b>${poly.name}</b><br>面积: ${formatArea(poly.area || 0)} ${getAreaUnitLabel()}`)
  })

  // 调整视野（包含预警点和所有多边形）
  if (currentWarning.value) {
    // 错误2修复：明确使用L.latLng创建坐标点，而不是使用数组
    const bounds = L.latLngBounds([
      L.latLng(currentWarning.value.lat, currentWarning.value.lng),
      ...polygons.value.flatMap(poly =>
        poly.points.map(p => L.latLng(p.lat, p.lng))
      )
    ])
    mapInstance.fitBounds(bounds, {padding: [50, 50], maxZoom: 15})
  }
}

/** 打开聚集预警详情页，传递完整行记录 */
const openGatherDetail = (row: WarnCommon) => {
  try {
    // 1. 再次确认id存在（排除id类型问题）
    if (row.gatherId === undefined || row.gatherId === null) {
      throw new Error('记录ID不存在，无法打开详情')
    }

    // 2. 单独序列化row，确保无异常（排查序列化失败）
    let rowDataStr: string;
    try {
      rowDataStr = JSON.stringify(row);
      // console.log('序列化后的数据:', rowDataStr); // 确认序列化结果
    } catch (serialError) {
      throw new Error(`数据序列化失败: ${(serialError as Error).message}`);
    }

    // 3. 编码并传递参数
    router.push({
      name: 'WarningGatherPerson',
      params: {
        id: row.gatherId.toString(), // 匹配路由的:id参数
      },
      query: {
        rowData: encodeURIComponent(rowDataStr) // 确保添加到query
      }
    });

    // 4. 验证跳转参数
    // console.log('跳转参数:', {
    //   params: {id: row.gatherId.toString()},
    //   query: {rowData: encodeURIComponent(rowDataStr)}
    // });

  } catch (error) {
    console.error('打开详情失败:', error);
    message.error(`打开详情失败: ${(error as Error).message}`);
  }
};

// 初始化所有数据
const getAllApi = async () => {
  try {
    loading.value = true
    await Promise.all([
      getList(),
      getWarnPage(),
      getWarnTypePie(),
    ])
  } finally {
    loading.value = false
  }
}

// 页面激活时重新加载数据
const reloadData = () => {
  getAllApi()
}

onMounted(reloadData)
</script>

<style lang="scss" scoped>
.description-content {
  line-height: 1.6;
  padding: 8px;
  background: #f8f8f8;
  border-radius: 4px;
}

:deep(.person-pagination) {
  .el-pager {
    li {
      width: 24px;
      height: 24px;
      line-height: 24px;
      border-radius: 50%;
      margin: 0 4px;

      &.active {
        background: var(--el-color-primary);
        color: white;
      }

      &:hover {
        background: var(--el-color-primary-light-9);
      }
    }
  }

  .btn-prev,
  .btn-next {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    padding: 0;
    min-width: auto;

    &:hover {
      background: var(--el-color-primary-light-9);
    }
  }
}

.case-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 16px;
}

.case-description {
  font-size: 16px;
  line-height: 1.6;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.add-btn {
  padding: 0 12px;
  height: 28px;
  font-size: 14px;
  border-radius: 4px;
  background-color: #f5f5f5;
}

/* 阴影分隔线样式 */
.header-divider {
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(0, 0, 0, 0.1), transparent);
  margin: 12px 0 16px 0;
  width: 100%;
}

.items-start {
  margin-top: 10px;
}

/* 调整抽屉样式 */
:deep(.el-drawer__body) {
  padding-top: 0 !important;
}

:deep(.el-drawer__header) {
  font-weight: bold;
  margin-bottom: 0 !important;
}

:deep(.el-divider--horizontal) {
  margin: 13px 0 !important;
}

.highlight-content {
  color: #000; // 与type和title保持一致的颜色
  // 如果需要单独设置高亮文本的颜色
  :deep(.highlight) {
    color: #000; // 高亮文本的颜色
    font-weight: 500;
  }
}
</style>
